package com.hh.service.service.impl.integral;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hh.common.constants.Constants;
import com.hh.common.exception.HhException;
import com.hh.common.model.express.Express;
import com.hh.common.model.integral.IntegralOrder;
import com.hh.common.model.integral.IntegralOrderInfo;
import com.hh.common.model.merchant.MerchantAdmin;
import com.hh.common.model.order.StoreOrderStatus;
import com.hh.common.model.user.User;
import com.hh.common.page.CommonPage;
import com.hh.common.request.PageParamRequest;
import com.hh.common.request.StoreOrderSearchRequest;
import com.hh.common.request.StoreOrderSendRequest;
import com.hh.common.response.StoreOrderCountItemResponse;
import com.hh.common.response.integral.IntegralAdminOrderDetailResponse;
import com.hh.common.response.integral.IntegralOrderDetailInfoResponse;
import com.hh.common.response.integral.IntegralOrderDetailResponse;
import com.hh.common.response.integral.IntegralOrderInfoResponse;
import com.hh.common.utils.DateUtil;
import com.hh.common.utils.SecurityUtil;
import com.hh.common.vo.MyRecord;
import com.hh.common.vo.dateLimitUtilVo;
import com.hh.common.vo.integral.StoreIntegralOrderInfoVo;
import com.hh.service.dao.integral.IntegralOrderDao;
import com.hh.service.delete.OrderUtils;
import com.hh.service.service.ExpressService;
import com.hh.service.service.UserService;
import com.hh.service.service.integral.IntegralOrderInfoService;
import com.hh.service.service.integral.IntegralOrderService;
import com.hh.service.service.integral.IntegralOrderStatusService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class IntegralOrderServiceImpl extends ServiceImpl<IntegralOrderDao, IntegralOrder> implements IntegralOrderService {

    @Resource
    private IntegralOrderDao dao;

    @Autowired
    private UserService userService;

    @Autowired
    private IntegralOrderService integralOrderService;

    @Autowired
    private OrderUtils orderUtils;

    @Autowired
    private IntegralOrderInfoService integralOrderInfoService;

    @Autowired
    private ExpressService expressService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private IntegralOrderStatusService integralOrderStatusService;

    /**
     * 创建积分订单
     * @param storeOrder
     * @return
     */
    @Override
    public boolean create(IntegralOrder storeOrder) {
        return dao.insert(storeOrder) > 0;
    }

    /**
     * 积分商城订单列表
     * @param status
     * @param keyword
     * @param pageRequest
     * @return
     */
    @Override
    public CommonPage<IntegralOrderDetailResponse> orderList(Integer status, String keyword, PageParamRequest pageRequest) {
        Integer userId = userService.getUserIdException();

        List<IntegralOrder> orderList = integralOrderService.getUserOrderList(userId, status,keyword, pageRequest);
        CommonPage<IntegralOrder> storeOrderCommonPage = CommonPage.restPage(orderList);
        List<IntegralOrderDetailResponse> responseList = CollUtil.newArrayList();
        for (IntegralOrder storeOrder : orderList) {
            IntegralOrderDetailResponse infoResponse = new IntegralOrderDetailResponse();
            BeanUtils.copyProperties(storeOrder, infoResponse);
            infoResponse.setPayPrice(storeOrder.getPayPrice().intValue());
            // 订单状态
            infoResponse.setOrderStatus(getH5OrderStatus(storeOrder));
            // 订单详情对象列表
            List<IntegralOrderInfo> orderInfoList = integralOrderInfoService.getListByOrderNo(storeOrder.getOrderId());
            List<IntegralOrderInfoResponse> infoResponseList = CollUtil.newArrayList();
            orderInfoList.forEach(e -> {
                IntegralOrderInfoResponse orderInfoResponse = new IntegralOrderInfoResponse();
                orderInfoResponse.setStoreName(e.getProductName());
                orderInfoResponse.setAttrId(e.getAttrValueId());
                orderInfoResponse.setImage(e.getImage());
                orderInfoResponse.setCartNum(e.getPayNum());
                orderInfoResponse.setPrice(e.getPrice());
                orderInfoResponse.setProductId(e.getProductId());
                orderInfoResponse.setSku(e.getSku());
                infoResponseList.add(orderInfoResponse);
            });
            infoResponse.setOrderInfoList(infoResponseList);
            responseList.add(infoResponse);
        }
        CommonPage<IntegralOrderDetailResponse> detailPage = CommonPage.restPage(responseList);
        BeanUtils.copyProperties(storeOrderCommonPage, detailPage, "list");
        return detailPage;
    }

    @Override
    public List<IntegralOrder> getUserOrderList(Integer userId, Integer status, String keyword, PageParamRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPage(), pageRequest.getLimit());
        LambdaQueryWrapper<IntegralOrder> lqw = new LambdaQueryWrapper<>();
        orderUtils.integralStatusApiByWhere(lqw, status);
        lqw.eq(IntegralOrder::getUid, userId);
        if(StrUtil.isNotBlank(keyword)){
            lqw.and(c->c.like(IntegralOrder::getOrderId,keyword).or().like(IntegralOrder::getKeywords,keyword));
        }
        lqw.orderByDesc(IntegralOrder::getId);
        return dao.selectList(lqw);
    }

    /**
     * 积分订单详情
     * @param orderId
     * @return
     */
    @Override
    public IntegralOrderDetailInfoResponse detailOrder(String orderId) {
        User currentUser = userService.getInfoException();

        IntegralOrderDetailInfoResponse storeOrderDetailResponse = new IntegralOrderDetailInfoResponse();
        // 查询订单
        IntegralOrder storeOrder = integralOrderService.getByOderId(orderId);
        if (ObjectUtil.isNull(storeOrder)) {
            throw new HhException("订单不存在");
        }
        if (!storeOrder.getUid().equals(currentUser.getUid())) {
            throw new HhException("订单不存在");
        }

        BeanUtils.copyProperties(storeOrder, storeOrderDetailResponse);

        MyRecord orderStatusVo = getOrderStatusVo(storeOrder);
        // 订单详情对象列表
        List<IntegralOrderInfoResponse> infoResponseList = CollUtil.newArrayList();
        List<IntegralOrderInfo> infoList = integralOrderInfoService.getListByOrderNo(storeOrder.getOrderId());
        infoList.forEach(e -> {
            IntegralOrderInfoResponse orderInfoResponse = new IntegralOrderInfoResponse();
            orderInfoResponse.setStoreName(e.getProductName());
            orderInfoResponse.setImage(e.getImage());
            orderInfoResponse.setCartNum(e.getPayNum());
            orderInfoResponse.setPrice(e.getPrice());
            orderInfoResponse.setProductId(e.getProductId());
            orderInfoResponse.setIsReply(e.getIsReply() ? 1 : 0);
            orderInfoResponse.setAttrId(e.getAttrValueId());
            orderInfoResponse.setSku(e.getSku());
            infoResponseList.add(orderInfoResponse);
        });
        storeOrderDetailResponse.setOrderInfoList(infoResponseList);
        storeOrderDetailResponse.setOrderStatus(orderStatusVo.getStr("title"));
        storeOrderDetailResponse.setOrderStatusMsg(orderStatusVo.getStr("msg"));
        storeOrderDetailResponse.setProTotalPrice(storeOrderDetailResponse.getProTotalPrice());
        return storeOrderDetailResponse;
    }

    @Override
    public IntegralOrder getByOderId(String orderId) {
        LambdaQueryWrapper<IntegralOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(IntegralOrder::getOrderId, orderId);
        return dao.selectOne(lqw);
    }

    /**
     * 确认收货
     * @param orderId
     * @return
     */
    @Override
    public Boolean take(String orderId) {
        IntegralOrder storeOrder = getByOrderIdException(orderId);

        if (!storeOrder.getStatus().equals(Constants.ORDER_STATUS_INT_SPIKE)) {
            throw new HhException("订单状态错误");
        }
        //已收货,就算完成了
        storeOrder.setStatus(Constants.ORDER_STATUS_INT_BARGAIN);
        storeOrder.setReceivingTime(DateUtil.nowDateTime());
        int i = dao.updateById(storeOrder);
        return i > 0;
    }

    @Override
    public CommonPage<IntegralAdminOrderDetailResponse> getAdminList(StoreOrderSearchRequest request, PageParamRequest pageParamRequest, boolean isMer) {
        Page<Object> startPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        QueryWrapper<IntegralOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "order_id", "uid", "real_name", "pay_price", "create_time", "status", "refund_status"
                , "refund_reason_wap_img", "refund_reason_wap_explain", "refund_reason_wap", "refund_reason", "refund_reason_time"
                , "is_del", "remark", "paid", "is_system_del", "shipping_type");

        if(isMer){
            String merId = SecurityUtil.getMerLoginUserVo().getUser().getMerId();
            queryWrapper.eq("mer_id",merId);
        }
        if (StrUtil.isNotBlank(request.getOrderNo())) {
            queryWrapper.eq("order_id", request.getOrderNo());
        }
        getRequestTimeWhere(queryWrapper, request);
        getStatusWhere(queryWrapper, request.getStatus());
        queryWrapper.orderByDesc("id");
        List<IntegralOrder> orderList = dao.selectList(queryWrapper);
        List<IntegralAdminOrderDetailResponse> detailResponseList = new ArrayList<>();
        if (CollUtil.isNotEmpty(orderList)) {
            detailResponseList = formatOrder1(orderList);
        }
        return CommonPage.restPage(CommonPage.copyPageInfo(startPage, detailResponseList));
    }

    @Override
    public StoreOrderCountItemResponse getOrderStatusNum(String dateLimit, boolean isMer) {
        String merId = Constants.PLATFORM_MER_ID;
        if(isMer){
            merId = SecurityUtil.getMerLoginUserVo().getUser().getMerId();
        }
        StoreOrderCountItemResponse response = new StoreOrderCountItemResponse();
        // 全部订单
        response.setAll(getCount(dateLimit, Constants.ORDER_STATUS_ALL,isMer,merId));
        // 未支付订单
        response.setUnPaid(getCount(dateLimit, Constants.ORDER_STATUS_UNPAID,isMer,merId));
        // 未发货订单
        response.setNotShipped(getCount(dateLimit, Constants.ORDER_STATUS_NOT_SHIPPED,isMer,merId));
        // 待收货订单
        response.setSpike(getCount(dateLimit, Constants.ORDER_STATUS_SPIKE,isMer,merId));
        // 待评价订单
        response.setBargain(getCount(dateLimit, Constants.ORDER_STATUS_BARGAIN,isMer,merId));
        // 交易完成订单
        response.setComplete(getCount(dateLimit, Constants.ORDER_STATUS_COMPLETE,isMer,merId));
        // 待核销订单
        response.setToBeWrittenOff(getCount(dateLimit, Constants.ORDER_STATUS_TOBE_WRITTEN_OFF,isMer,merId));
        // 退款中订单
        response.setRefunding(getCount(dateLimit, Constants.ORDER_STATUS_REFUNDING,isMer,merId));
        // 已退款订单
        response.setRefunded(getCount(dateLimit, Constants.ORDER_STATUS_REFUNDED,isMer,merId));
        // 已删除订单
        response.setDeleted(getCount(dateLimit, Constants.ORDER_STATUS_DELETED,isMer,merId));
        return response;
    }

    @Override
    public Boolean send(StoreOrderSendRequest request, boolean isMer) {
        String merId = Constants.PLATFORM_MER_ID;
        if(isMer){
            MerchantAdmin user = SecurityUtil.getMerLoginUserVo().getUser();
            merId = user.getMerId();
        }
        //订单信息
        IntegralOrder storeOrder = getInfoException(request.getOrderNo());
        if (storeOrder.getIsDel()) {
            throw new HhException("订单已删除,不能发货!");
        }
        if (storeOrder.getStatus() > 0) {
            throw new HhException("订单已发货请勿重复操作!");
        }
        request.setId(storeOrder.getId());

        express(request, storeOrder,isMer,merId);

        return true;
    }

    @Override
    public IntegralAdminOrderDetailResponse info(String orderNo) {
        IntegralOrder storeOrder = getInfoException(orderNo);
        if (storeOrder.getIsSystemDel()) {
            throw new HhException("未找到对应订单信息");
        }
        IntegralAdminOrderDetailResponse storeOrderInfoResponse = new IntegralAdminOrderDetailResponse();
        BeanUtils.copyProperties(storeOrder, storeOrderInfoResponse);
        List<StoreIntegralOrderInfoVo> orderInfos = integralOrderInfoService.getOrderListByOrderId(storeOrder.getId());
        storeOrderInfoResponse.setProductList(orderInfos);
        storeOrderInfoResponse.setStatusStr(getStatus(storeOrder));

        //用户信息
        User user = userService.getById(storeOrder.getUid());
        storeOrderInfoResponse.setNikeName(user.getNickname());
        storeOrderInfoResponse.setPhone(user.getPhone());


        storeOrderInfoResponse.setProTotalPrice(storeOrder.getTotalPrice().subtract(storeOrder.getTotalPostage()));
        return storeOrderInfoResponse;
    }


    /** 快递
     * @param request StoreOrderSendRequest 发货参数
     * @param storeOrder StoreOrder 订单信息
     */
    private void express(StoreOrderSendRequest request, IntegralOrder storeOrder,boolean isMer,String merId) {
        // 校验快递发货参数
        validateExpressSend(request);
        //快递公司信息
        Express express = expressService.getByCode(request.getExpressCode());

        deliverGoods(request, storeOrder);

        storeOrder.setDeliveryCode(express.getCode());
        storeOrder.setDeliveryName(express.getName());
        storeOrder.setStatus(1);
        storeOrder.setDeliveryTime(DateUtil.nowDateTime());
        storeOrder.setDeliveryType("express");

        String message = Constants.ORDER_LOG_MESSAGE_EXPRESS.replace("{deliveryName}", express.getName()).replace("{deliveryCode}", storeOrder.getDeliveryId());

        Boolean execute = transactionTemplate.execute(i -> {
            updateById(storeOrder);
            //订单记录增加
            integralOrderStatusService.createLog(request.getId(), Constants.ORDER_LOG_EXPRESS, message);
            return Boolean.TRUE;
        });

        if (!execute) {
            throw new HhException("快递发货失败！");
        }
    }

    /**
     * 正常发货
     */
    private void deliverGoods(StoreOrderSendRequest request, IntegralOrder storeOrder) {
        storeOrder.setDeliveryId(request.getExpressNumber());
    }

    /**
     * 校验快递发货参数
     */
    private void validateExpressSend(StoreOrderSendRequest request) {
        if (request.getExpressRecordType().equals("1")) {
            if (StrUtil.isBlank(request.getExpressNumber())) {
                throw new HhException("请填写快递单号");
            }
            return;
        }
        if (StrUtil.isBlank(request.getExpressCode())) {
            throw new HhException("请选择快递公司");
        }
        if (StrUtil.isBlank(request.getExpressRecordType())) {
            throw new HhException("请选择发货记录类型");
        }
        if (StrUtil.isBlank(request.getExpressTempId())) {
            throw new HhException("请选择电子面单");
        }
        if (StrUtil.isBlank(request.getToName())) {
            throw new HhException("请填写寄件人姓名");
        }
        if (StrUtil.isBlank(request.getToTel())) {
            throw new HhException("请填写寄件人电话");
        }
        if (StrUtil.isBlank(request.getToAddr())) {
            throw new HhException("请填写寄件人地址");
        }
    }

    private IntegralOrder getInfoException(String orderNo) {
        IntegralOrder integralOrder = getByOderId(orderNo);
        if(ObjectUtil.isNull(integralOrder)){
            throw new HhException("订单不存在");
        }
        return integralOrder;
    }


    /**
     * 获取订单总数
     * @param dateLimit 时间端
     * @param status String 状态
     * @return Integer
     */
    private Integer getCount(String dateLimit, String status,boolean isMer,String merId) {
        //总数只计算时间
        QueryWrapper<IntegralOrder> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(dateLimit)) {
            dateLimitUtilVo dateLimitUtilVo = DateUtil.getDateLimit(dateLimit);
            queryWrapper.between("create_time", dateLimitUtilVo.getStartTime(), dateLimitUtilVo.getEndTime());
        }
        getStatusWhereNew(queryWrapper, status);
        if(isMer){
            queryWrapper.eq("mer_id", merId);
        }
        return dao.selectCount(queryWrapper);
    }

    /**
     * 根据订单状态获取where条件
     * @param queryWrapper QueryWrapper<StoreOrder> 表达式
     * @param status String 类型
     */
    private void getStatusWhereNew(QueryWrapper<IntegralOrder> queryWrapper, String status) {
        if (StrUtil.isBlank(status)) {
            return;
        }
        switch (status) {
            case Constants.ORDER_STATUS_ALL: //全部
                break;
            case Constants.ORDER_STATUS_UNPAID: //未支付
                queryWrapper.eq("paid", 0);//支付状态
                queryWrapper.eq("status", 0); //订单状态
                queryWrapper.eq("is_del", 0);//删除状态
                break;
            case Constants.ORDER_STATUS_NOT_SHIPPED: //未发货
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("status", 0);
                queryWrapper.eq("refund_status", 0);
                queryWrapper.eq("shipping_type", 1);//配送方式
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_SPIKE: //待收货
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("status", 1);
                queryWrapper.eq("refund_status", 0);
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_BARGAIN: //待评价
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("status", 2);
                queryWrapper.eq("refund_status", 0);
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_COMPLETE: //交易完成
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("status", 3);
                queryWrapper.eq("refund_status", 0);
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_TOBE_WRITTEN_OFF: //待核销
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("status", 0);
                queryWrapper.eq("refund_status", 0);
                queryWrapper.eq("shipping_type", 2);//配送方式
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_REFUNDING: //退款中
                queryWrapper.eq("paid", 1);
                queryWrapper.in("refund_status", 1,3);
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_REFUNDED: //已退款
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("refund_status", 2);
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_DELETED: //已删除
                queryWrapper.eq("is_del", 1);
                break;
            default:
                queryWrapper.eq("paid", 1);
                queryWrapper.ne("refund_status", 2);
                break;
        }
        queryWrapper.eq("is_system_del", 0);
    }


    /**
     * 格式化订单信息，对外输出一致
     * @param orderList List<StoreOrder> 订单列表
     * @return List<StoreOrderItemResponse>
     */
    private List<IntegralAdminOrderDetailResponse> formatOrder1(List<IntegralOrder> orderList) {
        List<IntegralAdminOrderDetailResponse> detailResponseList  = new ArrayList<>();
        if (CollUtil.isEmpty(orderList)) {
            return detailResponseList;
        }

        //订单id集合
        List<Integer> orderIdList = orderList.stream().map(IntegralOrder::getId).distinct().collect(Collectors.toList());

        //获取订单详情map
        HashMap<Integer, List<StoreIntegralOrderInfoVo>> orderInfoList = integralOrderInfoService.getMapInId(orderIdList);
//
//        //根据用户获取信息
//        List<Integer> userIdList = orderList.stream().map(StoreOrder::getUid).distinct().collect(Collectors.toList());
//        //订单用户信息
//        HashMap<Integer, User> userList = userService.getMapListInUid(userIdList);

        for (IntegralOrder storeOrder : orderList) {
            IntegralAdminOrderDetailResponse storeOrderItemResponse = new IntegralAdminOrderDetailResponse();
            BeanUtils.copyProperties(storeOrder, storeOrderItemResponse);
            storeOrderItemResponse.setProductList(orderInfoList.get(storeOrder.getId()));

            //订单状态
            storeOrderItemResponse.setStatusStr(getStatus(storeOrder));
            storeOrderItemResponse.setStatus(storeOrder.getStatus());

            detailResponseList.add(storeOrderItemResponse);
        }
        return detailResponseList;
    }

    /**
     * 获取request的where条件
     * @param queryWrapper QueryWrapper<StoreOrder> 表达式
     * @param request StoreOrderSearchRequest 请求参数
     */
    private void getRequestTimeWhere(QueryWrapper<IntegralOrder> queryWrapper, StoreOrderSearchRequest request) {
        if (StringUtils.isNotBlank(request.getDateLimit())) {
            dateLimitUtilVo dateLimitUtilVo = DateUtil.getDateLimit(request.getDateLimit());
            queryWrapper.between("create_time", dateLimitUtilVo.getStartTime(), dateLimitUtilVo.getEndTime());
        }
    }

    /**
     * 获取订单状态
     * @param storeOrder StoreOrder 订单信息
     * @author Mr.Zhang
     * @since 2020-06-12
     */
    private Map<String, String> getStatus(IntegralOrder storeOrder) {
        Map<String, String> map = new HashMap<>();
        map.put("key", "");
        map.put("value", "");
        if (null == storeOrder) {
            return map;
        }
        // 未支付
        if (!storeOrder.getPaid()
                && storeOrder.getStatus() == 0
                && storeOrder.getRefundStatus() == 0
                && !storeOrder.getIsDel()
                && !storeOrder.getIsSystemDel()) {
            map.put("key", Constants.ORDER_STATUS_UNPAID);
            map.put("value", Constants.ORDER_STATUS_STR_UNPAID);
            return map;
        }
        // 未发货
        if (storeOrder.getPaid()
                && storeOrder.getStatus() == 0
                && storeOrder.getRefundStatus() == 0
                && storeOrder.getShippingType() == 1
                && !storeOrder.getIsDel()
                && !storeOrder.getIsSystemDel()) {
            map.put("key", Constants.ORDER_STATUS_NOT_SHIPPED);
            map.put("value", Constants.ORDER_STATUS_STR_NOT_SHIPPED);
            return map;
        }
        // 待收货
        if (storeOrder.getPaid()
                && storeOrder.getStatus() == 1
                && storeOrder.getRefundStatus() == 0
                && storeOrder.getShippingType() == 1
                && !storeOrder.getIsDel()
                && !storeOrder.getIsSystemDel()) {
            map.put("key", Constants.ORDER_STATUS_SPIKE);
            map.put("value", Constants.ORDER_STATUS_STR_SPIKE);
            return map;
        }
        // 待评价
        if (storeOrder.getPaid()
                && storeOrder.getStatus() == 2
                && storeOrder.getRefundStatus() == 0
                && !storeOrder.getIsDel()
                && !storeOrder.getIsSystemDel()) {
            map.put("key", Constants.ORDER_STATUS_BARGAIN);
            map.put("value", Constants.ORDER_STATUS_STR_BARGAIN);
            return map;
        }
        // 交易完成
        if (storeOrder.getPaid()
                && storeOrder.getStatus() == 3
                && storeOrder.getRefundStatus() == 0
                && !storeOrder.getIsDel()
                && !storeOrder.getIsSystemDel()) {
            map.put("key", Constants.ORDER_STATUS_COMPLETE);
            map.put("value", Constants.ORDER_STATUS_STR_COMPLETE);
            return map;
        }
        // 待核销
        if (storeOrder.getPaid()
                && storeOrder.getStatus() == 0
                && storeOrder.getRefundStatus() == 0
                && storeOrder.getShippingType() == 2
                && !storeOrder.getIsDel()
                && !storeOrder.getIsSystemDel()) {
            map.put("key", Constants.ORDER_STATUS_TOBE_WRITTEN_OFF);
            map.put("value", Constants.ORDER_STATUS_STR_TOBE_WRITTEN_OFF);
            return map;
        }

        //申请退款
        if (storeOrder.getPaid()
                && storeOrder.getRefundStatus() == 1
                && !storeOrder.getIsDel()
                && !storeOrder.getIsSystemDel()) {
            map.put("key", Constants.ORDER_STATUS_APPLY_REFUNDING);
            map.put("value", Constants.ORDER_STATUS_STR_APPLY_REFUNDING);
            return map;
        }

        //退款中
        if (storeOrder.getPaid()
                && storeOrder.getRefundStatus() == 3
                && !storeOrder.getIsDel()
                && !storeOrder.getIsSystemDel()) {
            map.put("key", Constants.ORDER_STATUS_REFUNDING);
            map.put("value", Constants.ORDER_STATUS_STR_REFUNDING);
            return map;
        }

        //已退款
        if (storeOrder.getPaid()
                && storeOrder.getRefundStatus() == 2
                && !storeOrder.getIsDel()
                && !storeOrder.getIsSystemDel()) {
            map.put("key", Constants.ORDER_STATUS_REFUNDED);
            map.put("value", Constants.ORDER_STATUS_STR_REFUNDED);
        }

        //已删除
        if (storeOrder.getIsDel() || storeOrder.getIsSystemDel()) {
            map.put("key", Constants.ORDER_STATUS_DELETED);
            map.put("value", Constants.ORDER_STATUS_STR_DELETED);
        }

        return map;
    }

    /**
     * 根据订单状态获取where条件
     * @param queryWrapper QueryWrapper<StoreOrder> 表达式
     * @param status String 类型
     */
    private void getStatusWhere(QueryWrapper<IntegralOrder> queryWrapper, String status) {
        if (StrUtil.isBlank(status)) {
            return;
        }
        switch (status) {
            case Constants.ORDER_STATUS_ALL: //未支付
                break;
            case Constants.ORDER_STATUS_UNPAID: //未支付
                queryWrapper.eq("paid", 0);//支付状态
                queryWrapper.eq("status", 0); //订单状态
                queryWrapper.eq("is_del", 0);//删除状态
                break;
            case Constants.ORDER_STATUS_NOT_SHIPPED: //未发货
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("status", 0);
                queryWrapper.eq("refund_status", 0);
                queryWrapper.eq("shipping_type", 1);//配送方式
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_SPIKE: //待收货
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("status", 1);
                queryWrapper.eq("refund_status", 0);
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_BARGAIN: //待评价
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("status", 2);
                queryWrapper.eq("refund_status", 0);
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_COMPLETE: //交易完成
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("status", 3);
                queryWrapper.eq("refund_status", 0);
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_TOBE_WRITTEN_OFF: //待核销
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("status", 0);
                queryWrapper.eq("refund_status", 0);
                queryWrapper.eq("shipping_type", 2);//配送方式
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_REFUNDING: //退款中
                queryWrapper.eq("paid", 1);
                queryWrapper.in("refund_status", 1,3);
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_REFUNDED: //已退款
                queryWrapper.eq("paid", 1);
                queryWrapper.eq("refund_status", 2);
                queryWrapper.eq("is_del", 0);
                break;
            case Constants.ORDER_STATUS_DELETED: //已删除
                queryWrapper.eq("is_del", 1);
                break;
            default:
                queryWrapper.eq("paid", 1);
                queryWrapper.ne("refund_status", 2);
                break;
        }
        queryWrapper.eq("is_system_del", 0);
    }

    private IntegralOrder getByOrderIdException(String orderId) {
        LambdaQueryWrapper<IntegralOrder> lwq = Wrappers.lambdaQuery();
        lwq.eq(IntegralOrder::getOrderId,orderId);
        IntegralOrder integralOrder = dao.selectOne(lwq);
        if(ObjectUtil.isNull(integralOrder)){
            throw new HhException("订单不存在");
        }
        return integralOrder;

    }


    /**
     * 获取订单状态相关信息
     * @return MyRecord
     */
    private MyRecord getOrderStatusVo(IntegralOrder storeOrder) {
        MyRecord record = new MyRecord();
        if (storeOrder.getRefundStatus() == 1) {
            record.set("type", -1);
            record.set("title", "申请退款中");
            record.set("msg", "商家审核中,请耐心等待");
        } else if (storeOrder.getRefundStatus() == 2) {
            record.set("type", -2);
            record.set("title", "已退款");
            record.set("msg", "已为您退款,感谢您的支持");
        } else if (storeOrder.getRefundStatus() == 3) {
            record.set("type", -3);
            record.set("title", "退款中");
            record.set("msg", "正在为您退款,感谢您的支持");
        } else if (storeOrder.getStatus() == 0) {
            record.set("type", 1);
            record.set("title", "未发货");
            record.set("msg", "商家未发货,请耐心等待");
        } else if (storeOrder.getStatus() == 1) { // 待收货处理
            // 待收货
            StoreOrderStatus storeOrderStatus = new StoreOrderStatus();
            storeOrderStatus.setOid(storeOrder.getId());
            storeOrderStatus.setChangeType(Constants.ORDER_LOG_EXPRESS);
            record.set("type", 2);
            record.set("title", "待收货");
            record.set("msg", "商家已发货,请耐心等待");

        }else if (storeOrder.getStatus() == 2) {
//            record.set("type", 3);
//            record.set("title", "待评价");
//            record.set("msg", "已收货,快去评价一下吧");
            record.set("type", 3);
            record.set("title", "交易完成");
            record.set("msg", "交易完成,感谢您的支持");
        }else if (storeOrder.getStatus() == 3) {
            record.set("type", 4);
            record.set("title", "交易完成");
            record.set("msg", "交易完成,感谢您的支持");
        }
        if (StringUtils.isNotBlank(storeOrder.getDeliveryType())) {
            record.set("deliveryType", StringUtils.isNotBlank(storeOrder.getDeliveryType()) ? storeOrder.getDeliveryType():"其他方式");
        }
        return record;
    }


    /**
     * 获取H5订单状态
     * @param storeOrder 订单对象
     */
    private String getH5OrderStatus(IntegralOrder storeOrder) {
        if (!storeOrder.getPaid()) {
            return "待支付";
        }
        if (storeOrder.getRefundStatus().equals(1)) {
            return "申请退款中";
        }
        if (storeOrder.getRefundStatus().equals(2)) {
            return "已退款";
        }
        if (storeOrder.getRefundStatus().equals(3)) {
            return "退款中";
        }
        if (storeOrder.getStatus().equals(0)) {
            return "待发货";
        }
        if (storeOrder.getStatus().equals(1)) {
            return "待收货";
        }
        if (storeOrder.getStatus().equals(2)) {
            return "待评价";
        }
        if (storeOrder.getStatus().equals(3)) {
            return "已完成";
        }
        return "";
    }
}
